package com.ruoyi.celoan.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.celoan.entity.DalianDataReportKeyEntity;
import com.ruoyi.celoan.entity.ExTradeEffectFinancingrequirementsDetailEntity;
import com.ruoyi.celoan.handanUtils.HanDanHttpUtils;
import com.ruoyi.celoan.handanUtils.response.CountryPlatformResponse;
import com.ruoyi.celoan.mapper.ExTradeEffectFinancingrequirementsDetailMapper;
import com.ruoyi.celoan.service.ExTradeEffectFinancingrequirementsDetailService;
import com.ruoyi.celoan.service.IEcDalianDataReportLogsService;
import com.ruoyi.celoan.util.DataReportUtil;
import com.ruoyi.celoan.util.ListUtils;
import com.ruoyi.common.utils.ObjUtil;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.manage.enterprise.domain.EcEnterpriseFinancingInfo;
import com.ruoyi.manage.enterprise.domain.EcEnterpriseInformation;
import com.ruoyi.manage.enterprise.service.IEcEnterpriseInformationService;
import com.ruoyi.manage.organization.domain.BizOrganizationDict;
import com.ruoyi.manage.organization.domain.OcBusinessFinancingOrder;
import com.ruoyi.manage.organization.service.IBizOrganizationDictService;
import com.ruoyi.manage.organization.service.IOcBusinessFinancingOrderService;
import com.xmsme.base.sdk.BaseApiClient;
import com.xmsme.base.sdk.response.StatisticsPostResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ExTradeEffectFinancingrequirementsDetailServiceImpl
        extends ServiceImpl<ExTradeEffectFinancingrequirementsDetailMapper, ExTradeEffectFinancingrequirementsDetailEntity>
        implements ExTradeEffectFinancingrequirementsDetailService {
    private static final Logger log = LoggerFactory.getLogger(ExTradeEffectFinancingrequirementsDetailServiceImpl.class);
    @Autowired
    private IEcDalianDataReportLogsService dalianDataReportLogsService;
    @Autowired
    private IEcEnterpriseInformationService ecEnterpriseInformationService;
    @Autowired
    private IOcBusinessFinancingOrderService orderService;
    @Autowired
    private IBizOrganizationDictService dictService;

    private static String url = "/api/upload/financingRequirements";

    public void getDataReport(String interfaceName, BaseApiClient client, DalianDataReportKeyEntity entity, String areaCode) {
        String startDate = LocalDateTime.now().plusDays(-2L).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        QueryWrapper<ExTradeEffectFinancingrequirementsDetailEntity> queryWrapper = new QueryWrapper();
        queryWrapper.eq("area_code", areaCode);
        queryWrapper.eq("isflag", Integer.valueOf(0));
        log.info("开始时间：" + startDate);
        List<ExTradeEffectFinancingrequirementsDetailEntity> list = ((ExTradeEffectFinancingrequirementsDetailMapper) this.baseMapper).selectList((Wrapper) queryWrapper);
        if (CollUtil.isNotEmpty(list)) {
            List<List<ExTradeEffectFinancingrequirementsDetailEntity>> retList = ListUtils.split(list, 100);
            this.dalianDataReportLogsService.addLogs(interfaceName + "接口上报数据开始", list.size() + "条");
            String date = LocalDate.now().toString();
            List<Long> updateList = new ArrayList<>();
            for (int i = 0; i < retList.size(); i++) {
                try {
                    List<ExTradeEffectFinancingrequirementsDetailEntity> reportList = retList.get(i);
                    List<Long> addlist = (List<Long>) reportList.stream().map(ret -> ret.getId()).collect(Collectors.toList());
                    this.dalianDataReportLogsService.addLogs(interfaceName + "明细日期:" + date + "上报id为：", JSONObject.toJSONString(addlist));
                    StatisticsPostResponse response = DataReportUtil.financingRequirements(reportList, client);
                    this.dalianDataReportLogsService.addLogs(interfaceName + "明细返回结果:", JSONObject.toJSONString(response));
                    if (response.isSuccess()) {
                        updateList.addAll(addlist);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("数据上报异常:" + e.getMessage());
                    this.dalianDataReportLogsService.addLogs(interfaceName + "上报数据上报错误信息", JSONObject.toJSONString(e.getMessage()));
                }
            }
            if (CollUtil.isNotEmpty(updateList)) {
                UpdateWrapper<ExTradeEffectFinancingrequirementsDetailEntity> updateWrapper = new UpdateWrapper();
                updateWrapper.in("id", updateList);
                updateWrapper.set("isflag", Integer.valueOf(1));
                update((Wrapper) updateWrapper);
                this.dalianDataReportLogsService.addLogs(interfaceName + "上报数据上报成功条数:", updateList.size() + "条");
            }
        }
    }

    public void getHanDanDataReport(String interfaceName, DalianDataReportKeyEntity entity, String areaCode, String token) {
        String startDate = LocalDateTime.now().plusDays(-2L).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        QueryWrapper<ExTradeEffectFinancingrequirementsDetailEntity> queryWrapper = new QueryWrapper();
        queryWrapper.eq("area_code", areaCode);
        queryWrapper.eq("isflag", Integer.valueOf(0));
        log.info("开始时间：" + startDate);
        List<ExTradeEffectFinancingrequirementsDetailEntity> list =  this.baseMapper.selectEnterpriseFinancingList();
        if (CollUtil.isNotEmpty(list)) {
            this.saveBatch(list);

            List<List<ExTradeEffectFinancingrequirementsDetailEntity>> retList = ListUtils.splitList(list, 1);
            this.dalianDataReportLogsService.addLogs(interfaceName + "接口上报数据开始", list.size() + "条");
            String date = LocalDate.now().toString();
            List<Long> updateList = new ArrayList<>();
            for (int i = 0; i < retList.size(); i++) {
                try {
                    List<ExTradeEffectFinancingrequirementsDetailEntity> reportList = retList.get(i);
                    List<Long> addlist = (List<Long>) reportList.stream().map(ret -> ret.getId()).collect(Collectors.toList());
                    this.dalianDataReportLogsService.addLogs(interfaceName + "明细日期:" + date + "上报id为：", JSONObject.toJSONString(addlist));
                    CountryPlatformResponse response = HanDanHttpUtils.financingRequirements(url, JSONObject.toJSONString(reportList), token);
                    this.dalianDataReportLogsService.addLogs(interfaceName + "明细返回结果:", JSONObject.toJSONString(response));
                    if (response.isApiStatus()) {
                        updateList.addAll(addlist);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("数据上报异常:" + e.getMessage());
                    this.dalianDataReportLogsService.addLogs(interfaceName + "上报数据上报错误信息", JSONObject.toJSONString(e.getMessage()));
                }
            }
            if (CollUtil.isNotEmpty(updateList)) {
                UpdateWrapper<ExTradeEffectFinancingrequirementsDetailEntity> updateWrapper = new UpdateWrapper();
                updateWrapper.in("id", updateList);
                updateWrapper.set("isflag", Integer.valueOf(1));
                update((Wrapper) updateWrapper);
                this.dalianDataReportLogsService.addLogs(interfaceName + "上报数据上报成功条数:", updateList.size() + "条");
            }
        }
    }


//  融资需求申请上报数据新增
    @Override
    public void addFinancingrequirementsDetail(EcEnterpriseFinancingInfo source){
        if(ObjUtil.isNull(source)){
            return;
        }
        ExTradeEffectFinancingrequirementsDetailEntity target = new ExTradeEffectFinancingrequirementsDetailEntity();
        EcEnterpriseInformation byId = ecEnterpriseInformationService.getById(source.getEnterpriseId());
        if(byId == null){
            return;
        }
        OcBusinessFinancingOrder order = orderService.getOne(new QueryWrapper<OcBusinessFinancingOrder>().eq("apply_id", source.getApplyNo()).last(" limit 1 "));
        if(order == null){
            return;
        }
        BizOrganizationDict dict = dictService.getOne(new QueryWrapper<BizOrganizationDict>().eq("org_name", order.getOrganizationName()).last(" limit 1 "));
        if(dict == null){
            return;
        }
        target.setId(target.getId());
        target.setUniscId(byId.getCreditCode()); // 统一社会信用代码
        target.setEnterpriseName(source.getEnterpriseName());
        target.setBankName(order.getOrganizationName());//金融机构名称    该字段应该在机构抢单成功成功后录入
        target.setBankCode(dict.getOrgCode());//金融机构编码    该字段应该在机构抢单成功成功后录入
        target.setAmount(source.getApplyAmountMax());//申请金额最小值 or 申请金额最大值
        target.setMaturity(Integer.valueOf(source.getMaturityMax()));//融资期限上限 or 融资期限下限
        target.setReleaseTime(source.getCreateTime());
        target.setOrientation("企业经营");//贷款用途
        target.setState(Integer.valueOf(order.getOrderState()));//需求进度状态
        target.setUpdateTime(source.getUpdateTime());
        target.setGuaranteeMode(target.getGuaranteeMode());
        target.setLoanRate(source.getRateMax());//利率上限 or 利率下限
        target.setRepaymentWays(Integer.valueOf(source.getRepaymentType()));
        target.setExternalSystemId(UUID.randomUUID().toString());
        target.setAreaCode(source.getAreaSiteId());
        target.setLoadTime(source.getUpdateTime());//加载时间
        target.setPlatformId(1306L);
        target.setProvince(source.getProvinceName());
        target.setCity(source.getCityName());
        target.setArea(source.getAreaName());

        boolean save = this.save(target);
    }
}


/* Location:              D:\tuodayun\workspace\work\celoan-third-data-report-service-2.0.0-SNAPSHOT.jar!\BOOT-INF\classes\com\celoan\service\impl\ExTradeEffectFinancingrequirementsDetailServiceImpl.class
 * Java compiler version: 8 (52.0)
 * JD-Core Version:       1.1.3
 */
